#!/bin/sh
#
# Perform necessary gitlab setup steps
# after package is installed.
#
DEST_DIR=<%= install_dir %>
EXTERNAL_URL="http://gitlab.example.com"

notify()
{
  echo "gitlab: $1"
}

create_config_template()
{
  # Create a minimal gitlab.rb template if /etc/gitlab/gitlab.rb does not exist.
  if ! [ -e /etc/gitlab/gitlab.rb ] ; then
    mkdir -p /etc/gitlab
    cp "${DEST_DIR}/etc/gitlab.rb.template" /etc/gitlab/gitlab.rb
    sed -i 's!GENERATED_EXTERNAL_URL!'$EXTERNAL_URL'!g' /etc/gitlab/gitlab.rb
    chmod 600 /etc/gitlab/gitlab.rb
  else
    EXTERNAL_URL=$(awk '/^external_url/ { print $2 }' /etc/gitlab/gitlab.rb | tr -d "'\"")
  fi
}

fix_directory_permissions()
{
  if [ -x /usr/bin/dpkg-query ] ; then
    # We are in the land of .deb packages. We should fix package directory owners
    # because of the faulty 7.2.0 / 7.2.1 .deb packages.
    /usr/bin/dpkg-query -L gitlab-ce gitlab-ee 2>/dev/null | while read f ; do
    if [ -d "$f" ] ; then
      # This directory may have been created when installing omnibus-gitlab
      # 7.2.0 / 7.2.1, so it could have the wrong owner.
      chown root:root "$f"
    fi
  done
fi
}

print_welcome()
{
  notify "Thank you for installing GitLab!"
  notify "To configure and start GitLab, RUN THE FOLLOWING COMMAND:"
  echo ""
  echo "sudo gitlab-ctl reconfigure"
  echo ""
  notify "GitLab should be reachable at ${EXTERNAL_URL}"
  notify "Otherwise configure GitLab for your system by editing /etc/gitlab/gitlab.rb file"
  notify "And running reconfigure again."
  notify
  notify "For a comprehensive list of configuration options please see the Omnibus GitLab readme"
  notify "https://gitlab.com/gitlab-org/omnibus-gitlab/blob/master/README.md"
  notify
}

check_if_ec2()
{
  if [ -f /sys/hypervisor/uuid ] && [ `head -c 3 /sys/hypervisor/uuid` = 'ec2' ]; then
    return 0
  else
    return 1
  fi
}

get_fqdn_from_hostname()
{
  # Try collecting fqdn if it is set correctly
  fqdn=$(/bin/hostname -f)
  if [ -n "${fqdn}" ]; then
    EXTERNAL_URL="http://${fqdn}"
  fi
}

get_ec2_hostname()
{
  # Try collecting fqdn if it is set correctly
  fqdn=$(/opt/gitlab/embedded/bin/curl -s http://169.254.169.254/latest/meta-data/public-hostname)
  if [ -n "${fqdn}" ]; then
    EXTERNAL_URL="http://${fqdn}"
  fi
}

if [ -n "${GITLAB_DEBUG}" ] ; then
  notify "debug: arguments: $@"
fi

check_if_ec2
if [ $? -eq 0 ]  ; then
  get_ec2_hostname
else
  get_fqdn_from_hostname
fi

${DEST_DIR}/embedded/bin/symlink_ctl_cmds ${DEST_DIR}
create_config_template
fix_directory_permissions
print_welcome

case "$1" in
  configure)
    # Looks like a DEB install. We don't know if it is a fresh install or an
    # upgrade.
    ${DEST_DIR}/bin/gitlab-ctl upgrade
    ;;
  *)
    # No op.
    ;;
esac
